package com.wanlian.service.impl;

import com.wanlian.common.ConstantCode;
import com.wanlian.common.IsHoliday;
import com.wanlian.common.PageCondition;
import com.wanlian.common.RankType;
import com.wanlian.dao.*;
import com.wanlian.entity.Card;
import com.wanlian.entity.Product;
import com.wanlian.entity.ScoreHistory;
import com.wanlian.entity.UserScore;
import com.wanlian.error.ErrorCode;
import com.wanlian.model.ResultModel;
import com.wanlian.service.ProductServices;
import com.wanlian.util.DateUtil;
import com.wanlian.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Calendar;
import java.util.List;


@Component
public class ProductServicesImpl implements ProductServices {

    @Autowired
    public ProductDao productDao;

    @Autowired
    public UserDao userDao;

    @Autowired
    public CardDao cardDao;
    @Autowired
    public UserScoreDao userScoreDao;

    @Autowired
    public ScoreHistoryDao scoreHistoryDao;

    /**
     * 添加商品
     *
     * @param product
     * @return
     */
    @Override
    public ResultModel doAdd(Product product) {
        ResultModel resultModel = new ResultModel();
        boolean isTrueType = RankType.isTrueType(product.getRankType());
        if (!isTrueType) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.RANK_TYPE_ERROR);
            return resultModel;
        }
        if (userDao.queryById(product.getUserId()) == null) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.NO_USER_ID);
            return resultModel;
        }
        Product dbProduct = this.productDao.queryByName(product.getName());
        if (dbProduct != null) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.PRODUCT_NAME_HASEXIST);
        } else {
            product.setStock(0);
            product.setVolume(0);
            this.productDao.add(product);
            resultModel.setBresult(true);
        }
        return resultModel;
    }

    /**
     * 修改商品
     *
     * @param product
     * @return
     */
    @Override
    public ResultModel doModify(Product product) {
        productDao.update(product);

        List<Card> cards=cardDao.queryCardsNoUsed(product.getId());
        for(Card card:cards){
            card.setImgPath(product.getImgPath());
            cardDao.update(card);
        }

        ResultModel resultModel = new ResultModel();
        resultModel.setMessage("修改成功");
        resultModel.setBresult(true);
        return resultModel;
    }

    /**
     * 启用商品
     *
     * @param product
     * @return
     */
    @Override
    public ResultModel doEnable(Product product) {
        ResultModel resultModel = new ResultModel();
        Product dbProduct = this.productDao.queryById(product.getId());
        if (!dbProduct.isEnable()) {
            dbProduct.setEnable(true);
            this.productDao.update(dbProduct);
            resultModel.setMessage("启用成功");
            resultModel.setBresult(true);
        } else {
            dbProduct.setEnable(false);
            resultModel.setBresult(true);
            this.productDao.update(dbProduct);
            resultModel.setMessage("禁用成功");
        }
        return resultModel;
    }

    /**
     * 删除商品
     *
     * @param product
     * @return
     */
    @Override
    public ResultModel doDelete(Product product) {
        ResultModel resultModel = new ResultModel();
        Product dbProduct = this.productDao.queryById(product.getId());
        if (dbProduct == null) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.PRODUCT_NO_EXIST);
        } else {
            if (dbProduct.isEnable()) {
                dbProduct.setEnable(false);
                this.productDao.update(dbProduct);
                resultModel.setBresult(true);
            } else {
                resultModel.setBresult(false);
                resultModel.setMessage(ErrorCode.PRODUCT_NO_ENABLE);
            }
        }
        return resultModel;
    }

    /**
     * 通过名称查询
     *
     * @param name
     * @param page
     * @return
     */
    @Override
    public ResultModel queryByName(String name, Page page) {
        return null;
    }

    /**
     * @param pageCondition
     * @return
     */
    @Override
    public ResultModel queryByPageCondition(PageCondition pageCondition) {
        return this.productDao.queryByPageCondition(pageCondition);
    }


    @Override
    public Product queryById(int id) {
        return this.productDao.queryById(id);
    }

    public ResultModel addProduct(PageCondition pageCondition, int userId) {
        ResultModel resultModel = new ResultModel();
        if (userId == 0) {
            userId = Integer.parseInt((String) pageCondition.getByKey("userId"));
        }
        //兑换时间为工作日9-16，今日兑换第二天0点生效
       try {
            if (IsHoliday.isHoliday()) {
                resultModel.setMessage("请于工作日9:00-16:00兑换");
                resultModel.setBresult(false);
                return resultModel;
            }
        } catch (ParseException e) {
            System.out.println(e);
        }
        // int
        int productRankType = Integer.parseInt((String) pageCondition.getByKey("rankType"));
        int productId = Integer.parseInt((String) pageCondition.getByKey("productId"));
        String pscore = pageCondition.getByKey("score") + "";
        pscore = pscore.replaceAll(",", "");
        double productScore = Float.parseFloat(pscore);
        //获取用户积分
        UserScore dbuserScore = userScoreDao.queryUserScoreByParams(userId, productRankType);
        if (dbuserScore == null) {
            resultModel.setMessage("该用户暂无积分");
        } else {
            double userScore = dbuserScore.getScore();
            if (userScore < productScore) {
                resultModel.setBresult(false);
                resultModel.setMessage("积分尚未达到商品价格，请赚取积分！");
            } else {
                //判断当天用户是否兑换，若兑换则返回
                long cardnum = cardDao.queryCardChanggeTimeById(userId);
                if (cardnum > 0) {
                    resultModel.setMessage("今日兑换次数已用完，请于第二个工作日9:00~16:00进行兑换");
                    resultModel.setBresult(false);
                } else {
                    //修改card表
                    Card card = cardDao.queryCardByProductId(productId);
                    if (card != null) {
                        card.setChangetime(DateUtil.currentTimestamp());
                        card.setUserId(userId);
                        card.setHasUsed(true);
                        cardDao.update(card);
                        resultModel.setBresult(true);
                        //修改商品库存销量
                        Product product = productDao.queryById(productId);
                        product.setStock(product.getStock() - 1);
                        product.setVolume(product.getVolume() + 1);
                        productDao.update(product);
                        //用户分数表减去商品分数
                        dbuserScore.setScore(userScore - productScore);
                        dbuserScore.setModifyTime(DateUtil.currentTimestamp());
                        userScoreDao.update(dbuserScore);
                        //添加用户积分流水
                        ScoreHistory scoreHistory = new ScoreHistory();
                        scoreHistory.setProductId(productId);
                        scoreHistory.setAddTime(DateUtil.currentTimestamp());
                        scoreHistory.setDeviceId("0");
                        scoreHistory.setTrantype(ConstantCode.TRANS_CHANGE);
                        scoreHistory.setScore(-productScore);
                        scoreHistory.setUserId(userId);
                        scoreHistory.setRankType(productRankType);
                        scoreHistoryDao.add(scoreHistory);
                        resultModel.setMessage("兑换成功");
                    } else {
                        resultModel.setMessage("暂无库存");
                    }
                }
            }
        }
        return resultModel;
    }

    ;
}
